package com.example.moshudriver.activity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.NotificationManager;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.BeeFramework.activity.BaseActivity;
import com.BeeFramework.model.BusinessResponse;
import com.BeeFramework.view.MyDialog;
import com.BeeFramework.view.ToastView;
import com.sgr.dykdriver.R;
import com.example.moshudriver.model.UserBalanceModel;
import com.example.moshudriver.protocol.ApiInterface;
import com.example.moshudriver.protocol.USER;
import com.example.moshudriver.tools.MessageConstant;
import com.example.moshudriver.tools.O2OMobileAppConst;
import com.example.moshudriver.tools.SESSION;
import com.example.moshudriver.tools.StreamTools;
import com.external.androidquery.callback.AjaxStatus;
import com.external.eventbus.EventBus;

//设置界面,弃置不用
public class F9_SettingActivity extends BaseActivity implements
		BusinessResponse, View.OnClickListener {
	protected static final int SHOW_UPDATE_DIALOG = 0;
	protected static final int URL_ERROR = 1;
	protected static final int NETWORK_ERROR = 2;
	protected static final int JSON_ERROR = 3;
	private TextView mTitle;
	private ImageView mBack;
	private Button mLogout;
	private SharedPreferences mShared;
	private SharedPreferences.Editor mEditor;
	private RelativeLayout mChangePassword;
	private RelativeLayout mFeedBack;
	private RelativeLayout mAbout;
	private UserBalanceModel mUserBalance;
	private USER mUser;
//	private RelativeLayout mVoice_switch;
	private RelativeLayout mUpdate;
	private NotificationManager mNotificationManager;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.f9_setting);
		mShared = getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
		mEditor = mShared.edit();
		mTitle = (TextView) findViewById(R.id.top_view_title);
		mTitle.setText(getString(R.string.setting));
		mBack = (ImageView) findViewById(R.id.top_view_back);
		mLogout = (Button) findViewById(R.id.btn_logout);
		String userStr = mShared.getString("user", "");
		try {
			if (userStr != null) {
				JSONObject userJson = new JSONObject(userStr);
				mUser = new USER();
				mUser.fromJson(userJson);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mChangePassword = (RelativeLayout) findViewById(R.id.change_password);
		mAbout = (RelativeLayout) findViewById(R.id.about);
		mFeedBack = (RelativeLayout) findViewById(R.id.feedback);
		mUpdate = (RelativeLayout) findViewById(R.id.update);
//		mVoice_switch = (RelativeLayout) findViewById(R.id.voice_switch);

		mUpdate.setOnClickListener(this);
//		mVoice_switch.setOnClickListener(this);
		mFeedBack.setOnClickListener(this);
		mAbout.setOnClickListener(this);
		mChangePassword.setOnClickListener(this);
		mBack.setOnClickListener(this);
		mLogout.setOnClickListener(this);
		mUserBalance = new UserBalanceModel(this);
		mUserBalance.addResponseListener(this);
	}

	@Override
	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException {
		if (url.endsWith(ApiInterface.USER_SIGNOUT)) {
			mEditor.putBoolean("isLogin", false);
			mEditor.putString("user", "");
			mEditor.putInt("uid", 0);
			mEditor.putString("sid", "");
			mEditor.commit();
			SESSION.getInstance().uid = mShared.getInt("uid", 0);
			SESSION.getInstance().sid = mShared.getString("sid", "");
			ToastView toast = new ToastView(F9_SettingActivity.this,
					getString(R.string.logout_success));
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
			Message msg = new Message();
			msg.what = MessageConstant.LOGINOUT;
			EventBus.getDefault().post(msg);
			Intent intent = new Intent(F9_SettingActivity.this,
					B0_SigninActivity.class);
			startActivity(intent);
			finish();
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.top_view_back:
			finish();
			break;
//		case R.id.voice_switch:
//			Toast.makeText(getApplicationContext(), "voice_switch", 0).show();
//			break;
		case R.id.btn_logout:
			Toast.makeText(getApplicationContext(), "您点击了btn_logout", 0).show();
			final MyDialog myDialog = new MyDialog(F9_SettingActivity.this,
					"是否注销该账户");
			myDialog.show();
			myDialog.positive.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					mUserBalance.signout();
					myDialog.dismiss();
				}
			});
			myDialog.negative.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					myDialog.dismiss();
				}
			});
			break;
		case R.id.change_password:
			Toast.makeText(getApplicationContext(), "您点击了change_password", 0)
					.show();
			intent = new Intent(F9_SettingActivity.this,
					C13_EditPasswordActivity.class);
			startActivity(intent);
			break;
		case R.id.about:
			Toast.makeText(getApplicationContext(), "您点击了about", 0).show();
			// intent = new Intent(F9_SettingActivity.this,
			// WebViewActivity.class);
			// intent.putExtra(WebViewActivity.WEBURL,
			// "http://www.o2omobile.com.cn");
			// startActivity(intent);
			break;
		case R.id.feedback:
			Toast.makeText(getApplicationContext(), "您点击了feedback", 0).show();
			intent = new Intent(F9_SettingActivity.this,
					C16_FeedbackActivity.class);
			startActivity(intent);
			break;
		case R.id.update:
			// Toast.makeText(getApplicationContext(), "您点击了更新", 0).show();
			// 检查更新
			checkUpdate();
			break;
		}
	}

	private String description;
	private String apkurl;

	private void checkUpdate() {
		new Thread() {

			public void run() {

				Message msg = Message.obtain();
				try {
					URL url = new URL(ApiInterface.UPDATE_URL);
					// 联网
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					// 请求方式
					conn.setRequestMethod("GET");
					// 请求超时时间
					conn.setConnectTimeout(4000);
					// 获取请求返回码
					int code = conn.getResponseCode();
					if (code == 200) {// 联网成功
						InputStream inputStream = conn.getInputStream();
						// 把流转化为string
						String result = StreamTools.readFromStream(inputStream);
						Log.i("联网情况：", "联网成功了" + result);
						// json解析
						JSONObject obj = new JSONObject(result);
						// 从服务器获取到版本信息
						String version = (String) obj.get("version");
						// String version = obj.getString("version");
						Log.i("version", version);
						// 版本描述
						description = (String) obj.get("description");
						Log.i("version", description);
						// apk的url
						apkurl = (String) obj.get("moshudriverapkurl");
						Log.i("version", apkurl);

						// 判断当前版本和服务器的是否匹配
						if (getVersionName().equals(version)) {
							// 版本一致，不需要进行更新
							Toast.makeText(F9_SettingActivity.this,
									"没有新版本,不需要更新", 0).show();
						} else {
							// 进行版本更新
							msg.what = SHOW_UPDATE_DIALOG;
						}
					}

				} catch (MalformedURLException e) {
					msg.what = URL_ERROR;
					e.printStackTrace();
				} catch (IOException e) {
					msg.what = NETWORK_ERROR;
					e.printStackTrace();
				} catch (JSONException e) {
					msg.what = JSON_ERROR;
					e.printStackTrace();
				} finally {
					handler.sendMessage(msg);
				}
			}

		}.start();

	}

	private Handler handler = new Handler() {
		// 处理消息
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case URL_ERROR:// URL错误
				Toast.makeText(getApplicationContext(), "URL错误", 0).show();
				break;
			case NETWORK_ERROR:// 网络异常
				Toast.makeText(F9_SettingActivity.this, "网络异常", 0).show();
				break;
			case JSON_ERROR:// JSON解析出错
				Toast.makeText(F9_SettingActivity.this, "JSON解析出错", 0).show();
				break;
			// 获取到新版本，显示升级的对话框
			case SHOW_UPDATE_DIALOG:
				showUpdateDialog();
				break;

			default:
				break;
			}
		}
	};

	// 显示升级对话框
	private void showUpdateDialog() {
		// TODO Auto-generated method stub

		Log.i("升级信息", "进行升级");

		AlertDialog.Builder builder = new Builder(F9_SettingActivity.this);
		builder.setTitle("提示升级");
		builder.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				dialog.dismiss();
			}
		});
		// 版本描述
		builder.setMessage(description);
		builder.setPositiveButton("立刻升级", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// 下载APK，并且替换安装
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					// sdcard存在
					// afnal
					FinalHttp finalhttp = new FinalHttp();
					finalhttp.download(apkurl, Environment
							.getExternalStorageDirectory().getAbsolutePath()
							+ "/MoShuDriver2.0.apk", new AjaxCallBack<File>() {

						@Override
						public void onFailure(Throwable t, int errorNo,
								String strMsg) {
							t.printStackTrace();
							Toast.makeText(getApplicationContext(), "下载失败", 1)
									.show();
							super.onFailure(t, errorNo, strMsg);
						}

						// 通知栏显示下载进度
						@Override
						public void onLoading(long count, long current) {
							// TODO Auto-generated method stub
							super.onLoading(count, current);

							mNotificationManager = (NotificationManager) getApplication()
									.getSystemService(NOTIFICATION_SERVICE);
							// 当前下载百分比
							int progress = (int) (current * 100 / count);
							NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
									getApplicationContext());
							mBuilder.setContentTitle("正在下载")
									.setContentText(progress + "%")
									.setSmallIcon(R.drawable.logo)
									.setAutoCancel(true)
									.setPriority(
											NotificationCompat.PRIORITY_MAX)
									.setTicker("正在下载最新版本");
							mNotificationManager.notify(0, mBuilder.build());
						}

						@Override
						public void onSuccess(File t) {
							// TODO Auto-generated method stub
							super.onSuccess(t);
							installAPK(t);
						}

						/**
						 * 安装APK
						 * 
						 * @param t
						 */
						private void installAPK(File t) {
							Intent intent = new Intent();
							intent.setAction("android.intent.action.VIEW");
							intent.addCategory("android.intent.category.DEFAULT");
							intent.setDataAndType(Uri.fromFile(t),
									"application/vnd.android.package-archive");
							startActivity(intent);
						}
					});
				} else {
					Toast.makeText(getApplicationContext(), "没有sdcard，请安装上再试",
							0).show();
					return;
				}
			}
		});
		builder.setNegativeButton("下次再说", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		builder.create();
		builder.show();
	}



	//得到版本信息
	private String getVersionName() {
		// 用来管理手机的APK
		PackageManager pManager = getPackageManager();
		try {
			// 得到知道APK的功能清单文件
			PackageInfo info = pManager.getPackageInfo(getPackageName(), 0);
			return info.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "";
		}
	};
}
